# !/usr/bin/python
# -*- coding: utf-8 -*-

# THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: 
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),  
# to deal in the Software without restriction, including without limitation  
# the rights to use, copy, modify, merge, publish, distribute, sublicense,  
# and/or sell copies of the Software, and to permit persons to whom the  
# Software is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in 
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
# DEALINGS IN THE SOFTWARE.

# drivers.py
# written by: 
#     Jan Jokela <jan@devion.org>

import os, sys
import musicbrainz2.webservice as ws
import urllib2

class MusicBrainz:
    def __init__(self):
        import musicbrainz2.webservice as ws
        import urllib2
    def parse(self, title, album, artist, length):
        self.title = title
        self.album = album
        self.artist = artist
        self.length = length
        
        try:
            q = ws.Query()
            filter = ws.TrackFilter(title=str(self.title), artistName=str(self.artist), releaseTitle=str(self.album), duration=self.length, limit=5)
        
            results = q.getTracks(filter=filter)
            bestresult = results[0]
            for result in results:
                if result.score > bestresult.score:
                    bestresult = result
            print str(bestresult.artist)
            print str(bestresult.releases)
            if self.album == 'None' and self.album == 'Unknown' and self.album == '' and self.album == None:
                    self.album = bestresult.releases
            if self.artist == 'None' and self.artist == 'Unknown' and self.artist == '' and self.artist == None:
                self.artist = bestresult.artist
        
        except:
            pass
        
        if self.album != 'None' and self.album != 'Unknown' and self.album != '' and self.album != None:
            try:
                q = ws.Query()
                if self.artist != 'None' and self.artist != 'Unknown' and self.artist != '' and self.artist != None:
                    filter = ws.ReleaseFilter(title=str(self.album), artistName=str(self.artist), limit=5)
                else:
                    filter = ws.ReleaseFilter(title=str(self.album), limit=5)
                results = q.getReleases(filter=filter)
                bestresult = results[0]
                for result in results:
                    if result.score > bestresult.score:
                        bestresult = result
                try:
                    print str(os.path.join(os.path.expanduser('~'), '.mediaplex', 'albumart', str(bestresult.release.asin) + '.jpg'))
                except: pass
                if os.path.exists(os.path.join(os.path.expanduser('~'), '.mediaplex', 'albumart', str(bestresult.release.asin) + '.jpg')):
                    self.album_art = os.path.join(os.path.expanduser('~'), '.mediaplex', 'albumart', str(bestresult.release.asin) + '.jpg')
                else:
                    picture_page = "http://ec1.images-amazon.com/images/P/" + str(bestresult.release.asin) + ".01._AA240_SCLZZZZZZZ_.jpg"
                    opener = urllib2.build_opener()
                    page = opener.open(picture_page)
                    my_picture = page.read()
                    filename = os.path.join(os.path.expanduser('~'), '.mediaplex', 'albumart', str(bestresult.release.asin) + picture_page[-4:])
                    print filename
                    fout = open(filename, "wb")
                    fout.write(my_picture)
                    fout.close()
                    self.album_art = filename                
            except: self.album_art = ''
        else: self.album_art = ''
        
    def get_artist(self):
        return self.artist
    def get_album(self):
        return self.album
    def get_album_art(self):
        return self.album_art
    